package com.iwhalecloud.bss.kite.cucc.service.util;

import java.util.Calendar;
import java.util.Objects;

import com.iwhalecloud.bss.kite.common.util.KiteStringUtils;
import com.iwhalecloud.bss.kite.cucc.common.constant.LocalKeyConsts;
import com.iwhalecloud.bss.kite.cucc.common.util.DateFormatUtils;
import com.iwhalecloud.bss.kite.manager.api.IOperateSceneInstService;
import com.iwhalecloud.bss.kite.manager.inst.KiteAttr;
import com.iwhalecloud.bss.kite.manager.inst.KiteInst;
import com.iwhalecloud.bss.kite.service.attr.AttrData;
import com.ztesoft.bss.common.util.SpringUtil;

public class CalculateExpireTimeUtil {
    /**
     * 处理失效时间
     */
    public static void dealExpireTime(KiteAttr attr, KiteInst inst, AttrData data) {
        IOperateSceneInstService operateSceneInstService = SpringUtil.getBean(IOperateSceneInstService.class);
        KiteAttr startDateAttr = inst.getAttr(LocalKeyConsts.STARTING_DATE_FIELD_NAME);
        KiteAttr endDateAttr = inst.getAttr(LocalKeyConsts.END_DATE_FIELD_NAME);
        //包月周期
        KiteAttr CycleMonthsAttr = inst.getAttr("200003242");
        //到期处理方式
        KiteAttr expirTreatment = inst.getAttr("210004553");
        if (Objects.nonNull(expirTreatment) && KiteStringUtils.equalsAny(expirTreatment.getValue(), LocalKeyConsts.END_UP_IN_PERIOD_TERMINATED, LocalKeyConsts.END_UP_IN_PERIOD_STOPPED)
            && KiteStringUtils.isNotEmpty(CycleMonthsAttr.getValue()) && KiteStringUtils.isNotEmpty(startDateAttr.getValue())) {
            //失效时间 = 生效时间 + 包周期月数
            Calendar cal = DateFormatUtils.parseStrToCalendar(startDateAttr.getValue());
            int startDay =cal.get(Calendar.DAY_OF_MONTH);
            cal.add(Calendar.MONTH, Integer.parseInt(CycleMonthsAttr.getValue()));
            int endDay =cal.get(Calendar.DAY_OF_MONTH);
            // 失效时间推N个月份中如果没有31、30、29需要取月份所在的最后一天
            if (endDay >= startDay) {
                cal.add(Calendar.DAY_OF_MONTH, -1);  //设置为前一天
            }
            int daySec = (60 * 60 * 24) - 1; // 一天的秒-1
            cal.add(Calendar.SECOND, daySec);
            String endDateStr = DateFormatUtils.formatDate(cal.getTime(), DateFormatUtils.DATE_TIME_FORMAT);
            endDateAttr.setValue(endDateStr);
            endDateAttr.setValueDesc(endDateStr);
            operateSceneInstService.setAttr(data.getSceneInstId(), inst.getInstType(), inst.getInstId(), endDateAttr);
        }
    }
}
